class Solution:
    def generateMatrix(self, n: int) -> List[List[int]]:
        # n = 1时特殊处理
        if n == 1:
            return [[1]]

        # 上下左右四个方向
        east, down, west, up = (0, 1), (1, 0), (0, -1), (-1, 0)
        matrix = [[0 for _ in range(n)] for _ in range(n)] # 空矩阵
        i = j = 0
        num = 1
        direction = 0 # 控制前进方向
        while num <= n * n:
            matrix[i][j] = num
            num += 1
            direction = direction % 4
            if direction == 0:
                i += east[0]
                j += east[1]
                if j + 1 == n or matrix[i][j + 1] != 0:
                    direction += 1
            elif direction == 1:
                i += down[0]
                j += down[1]
                if i + 1 == n or matrix[i + 1][j] != 0:
                    direction += 1
            elif direction == 2:
                i += west[0]
                j += west[1]
                if j - 1 < 0 or matrix[i][j - 1] != 0:
                    direction += 1
            else:
                i += up[0]
                j += up[1]
                if matrix[i - 1][j] != 0:
                    direction += 1
        return matrix